<template>
  <view class="new-page w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <text class="block text-[56rpx] font-extrabold mb-[48rpx] text-center text-blue-600 drop-shadow">人口学信息</text>

    <nut-form ref="formRef" :model-value="form" :rules="formRules" :label-width="120" class="max-w-[700rpx] w-full mx-auto box-border">
      <!-- 基本信息区域 -->
      <view class="bg-white rounded-[20rpx] shadow-[0_4rpx_24rpx_rgba(0,0,0,0.08)] p-[32rpx] mb-[32rpx] box-border">
        <text class="block text-[36rpx] font-bold mb-[32rpx] text-gray-800">👤 基本信息</text>

        <nut-form-item prop="name" label="姓名" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.name"
            placeholder="请输入姓名"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('name')"
          />
        </nut-form-item>

        <nut-form-item prop="sex" label="性别" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.sex"
            :columns="sexOptions"
            dictCode="sex"
            placeholder="请选择性别"
          />
        </nut-form-item>

        <nut-form-item prop="birthdate" label="出生日期" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.birthdate"
            placeholder="请输入出生日期(YYYY-MM-DD)"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('birthdate')"
          />
        </nut-form-item>

        <nut-form-item prop="birthPlace" label="出生地" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.birthPlace"
            placeholder="请输入出生地"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('birthPlace')"
          />
        </nut-form-item>

        <nut-form-item prop="nationality" label="民族" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.nationality"
            :columns="nationalityOptions"
            dictCode="nationality"
            placeholder="请选择民族"
          />
        </nut-form-item>

        <nut-form-item prop="nativePlace" label="籍贯" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.nativePlace"
            placeholder="请输入籍贯"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('nativePlace')"
          />
        </nut-form-item>

        <nut-form-item prop="tel" label="电话" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.tel"
            placeholder="请输入电话号码"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('tel')"
          />
        </nut-form-item>
      </view>

      <!-- 证件信息区域 -->
      <view class="bg-white rounded-[20rpx] shadow-[0_4rpx_24rpx_rgba(0,0,0,0.08)] p-[32rpx] mb-[32rpx] box-border">
        <text class="block text-[36rpx] font-bold mb-[32rpx] text-gray-800">🆔 证件信息</text>

        <nut-form-item prop="idType" label="证件类型" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.idType"
            :columns="idTypeOptions"
            dictCode="id_type"
            placeholder="请选择证件类型"
          />
        </nut-form-item>

        <nut-form-item prop="idNumber" label="证件号码" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.idNumber"
            placeholder="请输入证件号码"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('idNumber')"
          />
        </nut-form-item>
      </view>

      <!-- 社会信息区域 -->
      <view class="bg-white rounded-[20rpx] shadow-[0_4rpx_24rpx_rgba(0,0,0,0.08)] p-[32rpx] mb-[32rpx] box-border">
        <text class="block text-[36rpx] font-bold mb-[32rpx] text-gray-800">🏠 社会信息</text>

        <nut-form-item prop="marriType" label="婚姻状况" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.marriType"
            :columns="marriTypeOptions"
            dictCode="marri_type"
            placeholder="请选择婚姻状况"
          />
        </nut-form-item>

        <nut-form-item prop="eduType" label="文化程度" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.eduType"
            :columns="eduTypeOptions"
            dictCode="edu_type"
            placeholder="请选择文化程度"
          />
        </nut-form-item>

        <nut-form-item prop="jobType" label="职业" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.jobType"
            :columns="jobTypeOptions"
            dictCode="job_type"
            placeholder="请选择职业"
          />
        </nut-form-item>

        <nut-form-item prop="workPlace" label="工作单位/学校" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.workPlace"
            placeholder="请输入工作单位或学校"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('workPlace')"
          />
        </nut-form-item>

        <nut-form-item prop="liveType" label="常住类型" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.liveType"
            :columns="liveTypeOptions"
            dictCode="live_type"
            placeholder="请选择常住类型"
          />
        </nut-form-item>

        <nut-form-item prop="livePlace" label="常住地址" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.livePlace"
            placeholder="请输入常住地址"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('livePlace')"
          />
        </nut-form-item>
      </view>

      <!-- 健康信息区域 -->
      <view class="bg-white rounded-[20rpx] shadow-[0_4rpx_24rpx_rgba(0,0,0,0.08)] p-[32rpx] mb-[32rpx] box-border">
        <text class="block text-[36rpx] font-bold mb-[32rpx] text-gray-800">💊 健康信息</text>

        <nut-form-item prop="height" label="身高" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.height"
            placeholder="请输入身高(cm)"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('height')"
          />
        </nut-form-item>

        <nut-form-item prop="weight" label="体重" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.weight"
            placeholder="请输入体重(kg)"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('weight')"
          />
        </nut-form-item>

        <nut-form-item prop="bloodType" label="血型" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.bloodType"
            :columns="bloodTypeOptions"
            dictCode="blood_type"
            placeholder="请选择血型"
          />
        </nut-form-item>

        <nut-form-item prop="biosi" label="生物特征" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.biosi"
            placeholder="请输入生物特征"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('biosi')"
          />
        </nut-form-item>

        <nut-form-item prop="familyDoctor" label="家庭签约医生" class="mb-[32rpx] text-[32rpx]">
          <PickerInput
            v-model="form.familyDoctor"
            :columns="familyDoctorOptions"
            dictCode="yes_no"
            placeholder="请选择是否有家庭签约医生"
          />
        </nut-form-item>
      </view>

      <!-- 其他信息区域 -->
      <view class="bg-white rounded-[20rpx] shadow-[0_4rpx_24rpx_rgba(0,0,0,0.08)] p-[32rpx] mb-[32rpx] box-border">
        <text class="block text-[36rpx] font-bold mb-[32rpx] text-gray-800">📋 其他信息</text>

        <nut-form-item prop="religiousBeli" label="宗教信仰" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.religiousBeli"
            placeholder="请输入宗教信仰"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('religiousBeli')"
          />
        </nut-form-item>

        <nut-form-item prop="payType" label="医疗费用支付方式" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.payType"
            placeholder="请输入医疗费用支付方式"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('payType')"
          />
        </nut-form-item>

        <nut-form-item prop="payTypeOther" label="其他支付方式" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.payTypeOther"
            placeholder="请输入其他医疗费用支付方式"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('payTypeOther')"
          />
        </nut-form-item>

        <nut-form-item prop="orgName" label="档案管理机构" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.orgName"
            placeholder="请输入档案管理机构名称"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('orgName')"
          />
        </nut-form-item>

        <nut-form-item prop="orgTel" label="机构电话" class="mb-[32rpx] text-[32rpx]">
          <nut-input
            v-model="form.orgTel"
            placeholder="请输入档案管理机构电话"
            class="h-[88rpx] text-[32rpx] bg-gray-50 rounded-[12rpx] px-[24rpx]"
            @blur="() => validateField('orgTel')"
          />
        </nut-form-item>

        <nut-form-item prop="note" label="备注" class="mb-[32rpx] text-[32rpx]">
          <nut-textarea
            v-model="form.note"
            placeholder="请输入备注信息"
            class="min-h-[120rpx] text-[32rpx] !bg-gray-50 rounded-[12rpx] !px-[24rpx] !py-[16rpx] !border !border-[#d9d9d9] !border-opacity-100 !border-solid"
            @blur="() => validateField('note')"
          />
        </nut-form-item>
      </view>

      <!-- 操作按钮区域 -->
      <view class="flex gap-[24rpx] mt-[48rpx]">
        <nut-button
          block
          type="default"
          class="flex-1 flex-center"
          @click="resetForm"
        >
          <view class="flex items-center justify-center">
            <text class="text-gray-700 mr-[12rpx] text-[32rpx]">🔄</text>
            <text class="text-gray-700 text-[32rpx]">重置</text>
          </view>
        </nut-button>

        <nut-button
          block
          type="primary"
          class="flex-1 flex-center"
          @click="submitForm"
        >
          <view class="flex items-center justify-center">
            <text class="text-white mr-[12rpx] text-[32rpx]">💾</text>
            <text class="text-white text-[32rpx]">保存</text>
          </view>
        </nut-button>
      </view>
    </nut-form>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import PickerInput from '@/components/PickerInput.vue'
import { request } from '@/service/request'
import Taro from '@tarojs/taro'

// 表单数据
const form = reactive({
  name: '',
  sex: '',
  birthdate: '',
  birthPlace: '',
  nationality: '',
  nativePlace: '',
  tel: '',
  idType: '',
  idNumber: '',
  marriType: '',
  eduType: '',
  jobType: '',
  workPlace: '',
  liveType: '',
  livePlace: '',
  height: '',
  weight: '',
  bloodType: '',
  biosi: '',
  familyDoctor: '',
  religiousBeli: '',
  payType: '',
  payTypeOther: '',
  orgName: '',
  orgTel: '',
  note: ''
})

// 自定义验证函数
const nameLengthValidator = (val: string) => {
  if (!val) return Promise.resolve()
  if (val.trim().length >= 2) {
    return Promise.resolve()
  } else {
    return Promise.reject('姓名至少两个字符')
  }
}

const sexValidator = (val: any) => {
  if (val == 1 || val == 2) {
    return Promise.resolve()
  } else {
    return Promise.reject('请选择有效的性别')
  }
}

const birthdateValidator = (val: string) => {
  if (!val) return Promise.resolve()
  if (/^\d{4}-\d{2}-\d{2}$/.test(val)) {
    return Promise.resolve()
  } else {
    return Promise.reject('请输入正确的日期格式(YYYY-MM-DD)')
  }
}

const telValidator = (val: string) => {
  if (!val) return Promise.resolve()
  const telReg = /^1[3-9]\d{9}$/
  if (telReg.test(val)) {
    return Promise.resolve()
  } else {
    return Promise.reject('请输入正确的手机号码')
  }
}

const idNumberValidator = (val: string) => {
  if (!val) return Promise.resolve()
  const idReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (idReg.test(val)) {
    return Promise.resolve()
  } else {
    return Promise.reject('请输入正确的身份证号码')
  }
}

const heightValidator = (val: string) => {
  if (!val) return Promise.resolve()
  const height = parseFloat(val)
  if (!isNaN(height) && height >= 50 && height <= 250) {
    return Promise.resolve()
  } else {
    return Promise.reject('身高应在50-250cm之间')
  }
}

const weightValidator = (val: string) => {
  if (!val) return Promise.resolve()
  const weight = parseFloat(val)
  if (!isNaN(weight) && weight >= 10 && weight <= 300) {
    return Promise.resolve()
  } else {
    return Promise.reject('体重应在10-300kg之间')
  }
}

const formRef = ref()

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名' },
    {
      validator: nameLengthValidator,
      message: '姓名至少两个字符'
    }
  ],
  sex: [
    { required: true, message: '请选择性别' },
    {
      validator: sexValidator,
      message: '请选择有效的性别'
    }
  ],
  birthdate: [
    {
      validator: birthdateValidator,
      message: '请输入正确的日期格式(YYYY-MM-DD)'
    }
  ],
  tel: [
    {
      validator: telValidator,
      message: '请输入正确的手机号码'
    }
  ],
  idNumber: [
    {
      validator: idNumberValidator,
      message: '请输入正确的身份证号码'
    }
  ],
  height: [
    {
      validator: heightValidator,
      message: '请输入正确的身高(cm)'
    }
  ],
  weight: [
    {
      validator: weightValidator,
      message: '请输入正确的体重(kg)'
    }
  ]
})

// 选择器选项
const sexOptions = [[
  { text: '男', value: 0 },
  { text: '女', value: 1 },
  { text: '其他', value: 2 }
]]

const nationalityOptions = [[
  { text: '汉族', value: 1 },
  { text: '蒙古族', value: 2 },
  { text: '回族', value: 3 },
  { text: '藏族', value: 4 },
  { text: '维吾尔族', value: 5 },
  { text: '苗族', value: 6 },
  { text: '彝族', value: 7 },
  { text: '壮族', value: 8 },
  { text: '布依族', value: 9 },
  { text: '朝鲜族', value: 10 },
  { text: '满族', value: 11 },
  { text: '侗族', value: 12 },
  { text: '瑶族', value: 13 },
  { text: '白族', value: 14 },
  { text: '土家族', value: 15 },
  { text: '哈尼族', value: 16 },
  { text: '哈萨克族', value: 17 },
  { text: '傣族', value: 18 },
  { text: '黎族', value: 19 },
  { text: '傈僳族', value: 20 },
  { text: '佤族', value: 21 },
  { text: '畲族', value: 22 },
  { text: '高山族', value: 23 },
  { text: '拉祜族', value: 24 },
  { text: '水族', value: 25 },
  { text: '东乡族', value: 26 },
  { text: '纳西族', value: 27 },
  { text: '景颇族', value: 28 },
  { text: '柯尔克孜族', value: 29 },
  { text: '土族', value: 30 },
  { text: '达斡尔族', value: 31 },
  { text: '仫佬族', value: 32 },
  { text: '羌族', value: 33 },
  { text: '布朗族', value: 34 },
  { text: '撒拉族', value: 35 },
  { text: '毛南族', value: 36 },
  { text: '仡佬族', value: 37 },
  { text: '锡伯族', value: 38 },
  { text: '阿昌族', value: 39 },
  { text: '普米族', value: 40 },
  { text: '塔吉克族', value: 41 },
  { text: '怒族', value: 42 },
  { text: '乌孜别克族', value: 43 },
  { text: '俄罗斯族', value: 44 },
  { text: '鄂温克族', value: 45 },
  { text: '德昂族', value: 46 },
  { text: '保安族', value: 47 },
  { text: '裕固族', value: 48 },
  { text: '京族', value: 49 },
  { text: '塔塔尔族', value: 50 },
  { text: '独龙族', value: 51 },
  { text: '鄂伦春族', value: 52 },
  { text: '赫哲族', value: 53 },
  { text: '门巴族', value: 54 },
  { text: '珞巴族', value: 55 },
  { text: '基诺族', value: 56 },
  { text: '其他', value: 97 },
  { text: '外国血统', value: 98 }
]]

const idTypeOptions = [[
  { text: '身份证', value: 1 },
  { text: '护照', value: 2 },
  { text: '军官证', value: 3 },
  { text: '港澳通行证', value: 4 },
  { text: '台湾通行证', value: 5 },
  { text: '其他', value: 9 }
]]

const marriTypeOptions = [[
  { text: '未婚', value: 1 },
  { text: '已婚', value: 2 },
  { text: '丧偶', value: 3 },
  { text: '离婚', value: 4 },
  { text: '未说明的婚姻状况', value: 5 }
]]

const eduTypeOptions = [[
  { text: '文盲及半文盲', value: 1 },
  { text: '小学', value: 2 },
  { text: '初中', value: 3 },
  { text: '高中/技校/中专', value: 4 },
  { text: '大学专科及以上', value: 5 },
  { text: '不详', value: 6 }
]]

const jobTypeOptions = [[
  { text: '国家机关、党群组织、企业、事业单位负责人', value: 1 },
  { text: '专业技术人员', value: 2 },
  { text: '办事人员和有关人员', value: 3 },
  { text: '商业、服务业人员', value: 4 },
  { text: '农、林、牧、渔、水利业生产人员', value: 5 },
  { text: '生产、运输设备操作人员及有关人员', value: 6 },
  { text: '军人', value: 7 },
  { text: '不便分类的其他从业人员', value: 8 },
  { text: '退休', value: 9 },
  { text: '未知', value: 10 }
]]

const liveTypeOptions = [[
  { text: '城市', value: 1 },
  { text: '农村', value: 2 }
]]

const bloodTypeOptions = [[
  { text: 'A型', value: 'A型' },
  { text: 'B型', value: 'B型' },
  { text: 'AB型', value: 'AB型' },
  { text: 'O型', value: 'O型' },
  { text: '未知', value: '未知' }
]]

const familyDoctorOptions = [[
  { text: '否', value: 0 },
  { text: '是', value: 1 }
]]

// 字段验证方法
const validateField = async (fieldName: string) => {
  if (!formRef.value) return true
  try {
    const { valid, errors } = await formRef.value.validate(fieldName)
    return valid
  } catch (e) {
    return false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.reset()
  Object.keys(form).forEach(key => {
    (form as any)[key] = ''
  })
  Taro.showToast({
    title: '已重置',
    icon: 'success',
    duration: 1500
  })
}

const idNumber = ref('452225198403150039')
const recordid = ref('')
onMounted(async () => {
  // recordid.value = Taro.getStorageSync('recordid');
  if(recordid.value){
    // return
  }
  const params: any = {
    idNumber: idNumber.value
  }
  if(recordid.value){
    params.recordid = recordid.value
  }
  const res:any = await request.get('/health_records/HealthRecord/healthRecordInfo/list', params,{
    useErrMsg: true
  })
  if(res.success.records.length > 0){
    recordid.value = res.success.records[0].recordid;
    Taro.setStorageSync('recordid', recordid.value);

    const obj = res.success.records[0]
    for(let key in form){
      // if(obj[key] && key in form){
        (form as any)[key] = obj[key]
      // }
    }
    (form as any).id = obj.id;
  }
})

// 表单提交
const submitForm = async () => {
  try {
    const { valid, errors } = await formRef.value.validate();

    if (valid) {
      // 准备提交数据 - 直接使用API字段名
      const payload: any = { ...form }

      let url = '/health_records/HealthRecord/healthRecordInfo/add';
      if(recordid.value){
        url = '/health_records/HealthRecord/healthRecordInfo/edit';
        payload.recordid = recordid.value
      }
      const { error } = await request.post(url, payload, {
        useErrMsg: true
      })

      if (!error) {
        Taro.showToast({ title: '保存成功', icon: 'success', duration: 1500 })
        setTimeout(() => Taro.navigateBack(), 1200)
      } else {
        Taro.showToast({
          title: '保存失败，请重试',
          icon: 'error',
          duration: 2000
        })
      }
    } else {
      Taro.showToast({
        title: '请完善必填信息',
        icon: 'error',
        duration: 2000
      })
    }
  } catch (error) {
    Taro.showToast({
      title: '请完善必填信息',
      icon: 'error',
      duration: 2000
    })
  }
}
</script>

<style lang="scss">
.new-page{
  .nut-form-item {
    align-items: center;
  }
  .nut-input-box {
    align-items: center;
    padding: 0 20rpx;
    border: 1rpx solid #969696;
    border-radius: 10rpx;
    background-color: #f5f5f5;
  }
}
</style>
